package com.imooc.sell.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/*
 * @Description //cookie工具类
 * @Author whf15
 * @Date 14:15 2021/11/4
 * @Param
 * @return
 **/
public class CookieUtil {
    /*
     * @Description //设置
     * @Author whf15
     * @Date 14:22 2021/11/4
     * @Param [reponse, name, value, maxAge]
     * @return void
     **/
    public static void set(HttpServletResponse reponse,
                           String name,
                           String value,
                           int maxAge){
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        reponse.addCookie(cookie);
    }

    /*
     * @Description //获取cookie
     * @Author whf15
     * @Date 15:02 2021/11/4
     * @Param [request, name]
     * @return javax.servlet.http.Cookie
     **/
    public static Cookie get(HttpServletRequest request,
                           String name){
        Map<String, Cookie> cookieMap = readCookieMap(request);
        if(cookieMap.containsKey(name)){
            return cookieMap.get(name);
        }else{
            return null;
        }
    }


    /*
     * @Description //讲cookie封装成Map
     * @Author whf15
     * @Date 15:03 2021/11/4
     * @Param [request]
     * @return java.util.Map<java.lang.String,javax.servlet.http.Cookie>
     **/
    private static Map<String ,Cookie> readCookieMap(HttpServletRequest request){
        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}
